package com.jzo2o.trade.service.impl;

import cn.hutool.json.JSONUtil;
import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.Config;
import com.alipay.easysdk.payment.common.models.AlipayTradeRefundResponse;
import com.jzo2o.api.trade.dto.response.ExecutionResultResDTO;
import com.jzo2o.trade.model.domain.RefundRecord;
import com.jzo2o.trade.service.IAliRefundService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;


/**
 * \* User: chy
 * \* Date: 2025/10/10  14:54
 * \* Description:
 * \
 */
@Service
@Slf4j
public class AliRefundServiceImpl implements IAliRefundService {

    @Autowired
    @Qualifier("alipayConfig")
    private Config config;
    /**
     * 统一收单交易退款接口
     *
     * @param refundRecord
     * @return
     */
    @Override
    public ExecutionResultResDTO refund(RefundRecord refundRecord) {
        log.info("统一收单交易退款接口开始执行,订单单号为:{}", refundRecord.getTradingOrderNo());
        ExecutionResultResDTO execution = aliRefundRecord(refundRecord);
        return execution;
    }
    /**
     * 创建支付宝退款记录
     *
     * @param refundRecord
     */
    private ExecutionResultResDTO aliRefundRecord(RefundRecord refundRecord) {
        Factory.setOptions(config);
        try {
            // 创建支付宝退款记录,  第一个参数是支付单号，第二个参数是退款金额
            AlipayTradeRefundResponse refund = Factory.Payment.Common().refund(refundRecord.getTradingOrderNo(), refundRecord.getRefundAmount() + "");
           log.info("支付宝退款结果:{}", JSONUtil.toJsonStr(refund));
            // 封装返回结果
            ExecutionResultResDTO execution = new ExecutionResultResDTO();
            // 设置支付宝退款单号
            execution.setRefundId(refund.getTradeNo());
            // 设置支付宝退款状态
            execution.setRefundStatus(refund.getCode().hashCode());
            // 设置退款服务单号
            execution.setRefundNo(refundRecord.getRefundNo());
            return execution;
        } catch (Exception e) {
            log.error("支付宝退款异常:{}", e);
            return null;
        }

    }
}
